package com.jpyl.jpMedicalTreatment.view.activity.self;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.google.gson.JsonObject;
import com.jpyl.jpMedicalTreatment.R;
import com.jpyl.jpMedicalTreatment.model.AgentMessageModel;
import com.jpyl.jpMedicalTreatment.model.ErrorMessageModel;
import com.jpyl.jpMedicalTreatment.model.ResponseModel;
import com.jpyl.jpMedicalTreatment.model.RxSpf_UserModel;
import com.jpyl.jpMedicalTreatment.model.helper.DeliveryListModel;
import com.jpyl.jpMedicalTreatment.network.Const;
import com.jpyl.jpMedicalTreatment.network.Network;
import com.jpyl.jpMedicalTreatment.network.api.ApiError;
import com.jpyl.jpMedicalTreatment.network.api.RequestApi;
import com.jpyl.jpMedicalTreatment.view.activity.BaseActivity;
import com.jpyl.jpMedicalTreatment.view.adapter.DeliveryAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 待发货，已发货界面
 * 0全部订单 1未支付 2待发货 3已发货 4申请退款
 * Created by 15697 on 2019/2/28.
 */

public class DeliveryActivity extends BaseActivity {
    @BindView(R.id.rv_refresh_layout)
    RecyclerView rvRefreshLayout;
    @BindView(R.id.mr_refresh_layout)
    MaterialRefreshLayout mrRefreshLayout;
    @BindView(R.id.tv_refreshLayout_Empty)
    TextView tvRefreshLayoutEmpty;

    DeliveryAdapter adapter;
    int flag;
    int page = 1, listSize, type = -1;
    final RequestApi publicApi = Network.getRequestApi();
    RxSpf_UserModel spfUserModel;
    List<DeliveryListModel.Datas> list = new ArrayList<>();
    String userId = "";
    List<AgentMessageModel> lists = new ArrayList<>();
    int state;////大区代理查询所有未发货和已发货订单（大区代理id，0未发货 1已发货）

    @Override
    protected int getLayoutId() {
        return R.layout.activity_refrsh_layout;
    }

    @Override
    public void afterCreate(Bundle savedInstanceState) {
        spfUserModel = RxSpf_UserModel.create(this);
        userId = spfUserModel.userId().get();
        flag = getIntent().getIntExtra
                ("flag", -1);
        switch (flag) {
            case Const.TOSHIPPED:
                mTitleTv.setText(R.string.mine_toBeShipped);
                type = 2;
                state = 0;
                break;
            case Const.SHIPPED:
                type = 3;
                state = 1;
                mTitleTv.setText(R.string.mine_shipped);
                break;
        }
        adapter = new DeliveryAdapter(this, list, flag);
        rvRefreshLayout.setAdapter(adapter);
        adapter.setItemClickListener(new DeliveryAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {

            }
        });

        rvRefreshLayout.setLayoutManager(new GridLayoutManager(this, 1));
        mrRefreshLayout.setLoadMore(true);
        mrRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                //刷新
                page = 1;
                getList();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                super.onRefreshLoadMore(materialRefreshLayout);
                //加载更多
                if (10 == listSize) {
                    ++page;
                    getList();
                } else {
                    materialRefreshLayout.finishRefreshLoadMore();
                }
            }
        });
        getList();
    }

    private void getList() {
        if (spfUserModel.type().get().equals("1")) {
            //患者
            jpylBuyerOrders(userId);
        }
        if (spfUserModel.type().get().equals("2")) {
            //医生
            jpylQueryDoctorsByName();
        }
        if (spfUserModel.type().get().equals("3")) {
            //大区代理
            jpylAgentShipOrders();
        }
        if (spfUserModel.type().get().equals("4")) {
            //总代理商
            jpylOwnerShipOrders();
        }

    }

    private void jpylQueryDoctorsByName() {
        String userid = spfUserModel.userId().get();
        publicApi.jpylQueryMyPatientsByName(userid, "").map(new Func1<ResponseModel<List<AgentMessageModel>>, List<AgentMessageModel>>() {
            @Override
            public List<AgentMessageModel> call(ResponseModel<List<AgentMessageModel>>
                                                        responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<AgentMessageModel>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mrRefreshLayout.finishRefreshing();
                        mrRefreshLayout.finishRefresh();
                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                        } else {
                        }
                    }

                    @Override
                    public void onNext(List<AgentMessageModel> list) {
                        mrRefreshLayout.finishRefreshing();
                        mrRefreshLayout.finishRefresh();
                        lists.clear();
                        lists.addAll(list);
                        for (int i = 0; i < list.size(); i++) {
                            jpylBuyerOrders(list.get(i).getId());
                        }
                    }
                });
    }

    private void jpylBuyerOrders(String userIds) {
        final JsonObject body = new JsonObject();
        body.addProperty("rows", "10");
        body.addProperty("page", page);
        publicApi.jpylBuyerOrders(userIds, body.toString(), type).map(new Func1<ResponseModel<DeliveryListModel>, DeliveryListModel>() {
            @Override
            public DeliveryListModel call(ResponseModel<DeliveryListModel>
                                                  responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<DeliveryListModel>() {
                    @Override
                    public void onCompleted() {
                        mrRefreshLayout.finishRefreshLoadMore();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshing();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mrRefreshLayout.finishRefreshLoadMore();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshing();
                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                        } else {
                        }
                    }

                    @Override
                    public void onNext(DeliveryListModel bean) {
                        mrRefreshLayout.finishRefreshLoadMore();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshing();
                        listSize = bean.getTotal();
                        if (page == 1) {
                            list.clear();
                        }
                        list.addAll(bean.getRows());
                        adapter.notifyDataSetChanged();
                    }
                });
    }

    private void jpylAgentShipOrders() {

        final JsonObject body = new JsonObject();
        body.addProperty("rows", "10");
        body.addProperty("page", "1");


        publicApi.jpylAgentShipOrders(userId, body.toString(), state).map(new Func1<ResponseModel<DeliveryListModel>, DeliveryListModel>() {
            @Override
            public DeliveryListModel call(ResponseModel<DeliveryListModel> responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<DeliveryListModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mrRefreshLayout.finishRefreshing();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshLoadMore();
                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                        } else {
                        }
                    }

                    @Override
                    public void onNext(DeliveryListModel object) {
                        mrRefreshLayout.finishRefreshing();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshLoadMore();
                        listSize = object.getTotal();
                        if (page == 1) {
                            list.clear();
                        }
                        list.addAll(object.getRows());
                        adapter.notifyDataSetChanged();
                    }
                });
    }

    private void jpylOwnerShipOrders() {
        final JsonObject body = new JsonObject();
        body.addProperty("rows", "10");
        body.addProperty("page", "1");

        publicApi.jpylAreaAgentShipOrders(userId, body.toString(), state).map(new Func1<ResponseModel<DeliveryListModel>, DeliveryListModel>() {
            @Override
            public DeliveryListModel call(ResponseModel<DeliveryListModel>
                                                  responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<DeliveryListModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                        } else {
                        }
                    }

                    @Override
                    public void onNext(DeliveryListModel lists) {
                        mrRefreshLayout.finishRefreshing();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshLoadMore();
                        listSize = lists.getTotal();
                        if (page == 1) {
                            list.clear();
                        }
                        list.addAll(lists.getRows());
                        adapter.notifyDataSetChanged();
                    }
                });
    }
}
